import 'package:aichat_flutter_wallet/module/module_integral/model/integral_api.dart';
import 'package:aichat_flutter_wallet/module/module_integral/model/integral_model.dart';
import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_database/sp.dart';
import 'package:lib_language/lib_language.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../../kai_print.dart';

class CheckCalendarPage extends StatefulWidget {
  CheckCalendarPage({
    super.key,
  });

  @override
  State<CheckCalendarPage> createState() => _CheckCalendarPageState();
}

class _CheckCalendarPageState extends State<CheckCalendarPage> {
  List<SignInData> signList = [];
  DateFormat dateFormat = DateFormat('yyyy-MM-dd');
  String historyDate = '';
  DateTime nowTime = DateTime(DateTime.now().year, DateTime.now().month, 1);
  Widget Calendar() {
    return Container(
      height: 372.w,
      decoration: BoxDecoration(
          image: DecorationImage(image: AssetImage("assets/images/integral/calendar_bg.png"), fit: BoxFit.cover)),
      child: TableCalendar(
          locale: 'en_US',
          rowHeight: 35.w,
          daysOfWeekHeight: 30.w,
          firstDay: DateTime.utc(2010, 12, 31),
          lastDay: DateTime.utc(2050, 12, 31),
          focusedDay: nowTime,
          calendarBuilders: CalendarBuilders(
            headerTitleBuilder: (context, day) {
              return Container(
                height: 60.w,
                padding: EdgeInsets.only(top: 10.w),
                child: Center(
                  child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                    Text(
                      DateFormat.LLL('en_US').format(day),
                      style: TextStyle(color: AppColors.c_333333, fontSize: 14.sp, fontWeight: FontWeight.w500),
                    ),
                    SizedBox(
                      width: 3.w,
                    ),
                    Text(
                      DateFormat.y('en_US').format(day),
                      style: TextStyle(color: AppColors.c_333333, fontSize: 14.sp, fontWeight: FontWeight.w500),
                    ),
                  ]),
                ),
              );
            },
            weekNumberBuilder: (context, day) {
              // final text = DateFormat.E('en_US').format(day);
              return Container(
                height: 42.w,
                child: Center(
                  child: Text(
                    day.toString(),
                    style: TextStyle(color: AppColors.c_868391, fontWeight: FontWeight.w400, fontSize: 14.sp),
                  ),
                ),
              );
            },
            defaultBuilder: (BuildContext context, DateTime day, DateTime focusedDay) {
              final text = DateFormat.d('en_US').format(day);
              return Container(
                height: 22.w,
                width: 22.w,
                child: Center(
                  child: isSign(day)
                      ? Selected()
                      : Text(
                          text,
                          style: TextStyle(color: AppColors.c_333333, fontWeight: FontWeight.w500, fontSize: 14.sp),
                        ),
                ),
              );
            },
            outsideBuilder: (BuildContext context, DateTime day, DateTime focusedDay) {
              final text = DateFormat.d('en_US').format(day);
              return Container(
                height: 22.w,
                width: 22.w,
                child: Center(
                  child: isSign(day)
                      ? Selected()
                      : Text(
                          text,
                          style: TextStyle(color: AppColors.c_BEBDCA, fontWeight: FontWeight.w500, fontSize: 14.sp),
                        ),
                ),
              );
            },
            todayBuilder: (BuildContext context, DateTime day, DateTime focusedDay) {
              final text = DateFormat.d('en_US').format(day);
              return Container(
                height: 22.w,
                width: 22.w,
                decoration:
                    BoxDecoration(color: AppColors.c_F6F6F6, borderRadius: BorderRadius.all(Radius.circular(11))),
                child: Center(
                  child: isSign(day)
                      ? Selected()
                      : Text(
                          text,
                          style: TextStyle(color: AppColors.c_BEBDCA, fontWeight: FontWeight.w500, fontSize: 14.sp),
                        ),
                ),
              );
            },
          ),
          headerStyle: HeaderStyle(
            formatButtonVisible: false,
            titleTextStyle: TextStyle(fontSize: 17.sp),
            headerPadding: EdgeInsets.symmetric(vertical: 8.w),
            leftChevronMargin: EdgeInsets.only(left: 110.w, right: 0, top: 10.w),
            rightChevronMargin: EdgeInsets.only(right: 110.w, left: 0, top: 10.w),
            leftChevronPadding: EdgeInsets.zero,
            rightChevronPadding: EdgeInsets.zero,
            // leftChevronVisible: false,
            // rightChevronVisible: false,
          ),
          calendarStyle:
              CalendarStyle(outsideDecoration: BoxDecoration(), tablePadding: EdgeInsets.fromLTRB(32.w, 5.w, 32.w, 0)),
          onPageChanged: (DateTime day) {
            nowTime = day;
            // DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(day.millisecondsSinceEpoch);
            // String monthZero = '';
            // String dayZero = '';
            // if (dateTime.month < 10) monthZero = '0';
            // if (dateTime.day < 10) dayZero = '0';
            // historyDate =
            //     "${dateTime.year}-${monthZero + dateTime.month.toString()}-${dayZero + dateTime.day.toString()}";
            historyDate = dateFormat.format(nowTime);
            getSignDate();
          }),
    );
  }

  @override
  void initState() {
    super.initState();
    getSignDate();
  }

  Future getSignDate() async {
    try {
      if (historyDate == '') {
        historyDate = dateFormat.format(DateTime.now());
      }
      String str = historyDate;
      final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      List<SignInData> sparr = await SP().getSigninList(userId, str);
      if (sparr.length > 0)
        setState(() {
          signList = sparr;
        });

      List<TaskSignDateItem> hisData = await IntegralApi.getSignDate2(historyDate: str);
      List<SignInData> arr = hisData.map((e) => SignInData(days: e.day, start: e.start)).toList();
      await SP().setSigninList(arr, userId, historyDate);
      if (str == historyDate && mounted) {
        setState(() {
          signList = arr;
        });
      }
    } catch (e) {
      kaiPrint(e);
    }
  }

  saveLocal(List<TaskSignDateItem> list, historyDate) async {
    try {} catch (e) {
      kaiPrint(e);
    }
  }

  //是否签到
  bool isSign(DateTime day) {
    if (signList.length == 0) return false;
    int timestamp = day.millisecondsSinceEpoch;
    List<SignInData> newList =
        signList.where((item) => DateTime.parse(item.start).millisecondsSinceEpoch < timestamp).toList();
    if (newList.length == 0) return false;
    SignInData obj = newList[newList.length - 1];
    int time =
        DateTime.parse(obj.start).millisecondsSinceEpoch + int.parse((obj.days * 24 * 60 * 60 * 1000).toString());
    return time > timestamp;
  }

  Widget Selected() {
    return Image.asset(
      'assets/images/integral/selected.png',
      width: 22.w,
      height: 22.w,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
            image: DecorationImage(image: AssetImage("assets/images/integral/detail_bg.png"), fit: BoxFit.fitHeight),
            color: AppColors.c_F6F6F6),
        child: Column(children: [
          PageHeaderCom(title: 'Check Calendar', bgColor: Colors.transparent, showBottomBorder: false),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            child: Calendar(),
          )
        ]),
      ),
    );
  }
}
